<template>
  <transition name="fade">
    <div class="mask" v-if="visible">
      <div class="lm-tost">
        <span class="lm-toast-content">{{ message }}</span>
      </div>
    </div>
  </transition>
</template>
<script>
export default {
  name: "LmToast",
  props: {
    message: {
      type: String,
      default: "",
    },
    duration: {
      // 自动关闭时间
      type: Number,
      default: 3000,
    },
    autoClose: {
      // 是否开启自动关闭
      type: Boolean,
      default: true,
    },
    onClose: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      visible: false,
    };
  },
  mounted() {
    if (this.autoClose) {
      this.startTimer();
    }
    this.createElement();
  },
  beforeDestroy() {
    //   移除
    this.$el.parentNode.removeChild(this.$el);
  },
  methods: {
    createElement() {
      this.visible = true;
      document.body.appendChild(this.$el);
    },
    startTimer() {
      let timer = setTimeout(() => {
        this.visible = false;
      }, this.duration);
      this.$once("hook:beforeDestory", () => {
        clearTimeout(timer);
        timer = null;
      });
    },
  },
  watch: {
    visible(newVal) {
      if (!newVal) {
        this.$el.addEventListener("transitionend", () => {
          this.$destroy();
        });
        this.$emit("onClose");
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../style/common.scss";

.mask {
  @include mask();
  background: rgba(0, 0, 0, 0);
}

.lm-toast-content {
  color: #fff;
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.8);
  padding: 10px;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
  transform: scale(0.5);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s, transform 0.5s;
}
</style>